package com.epoch.server.kernel.dao;

import com.epoch.common.Message;
import com.epoch.server.kernel.utils.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

/**
 * @author Seon
 * @date 2022/10/20 18:33
 */
public class ChatRecordDao {
    Connection con = DBUtil.getConnectDB();

    public boolean addRecord(Message mes) throws SQLException {
        boolean judge = false;

        String sql = "insert into chat_record (record, sending_time, sender, `group`) values (?,?,?,?)";
        PreparedStatement ps = con.prepareStatement(sql);
        ps.setString(1, mes.getMessage());
        ps.setString(2, mes.getDate());
        ps.setInt(3, mes.getSender());
        ps.setInt(4, mes.getGroupId());

        if(ps.executeUpdate() == 1){
            judge = true;
        }
        return judge;
    }

    /**
     * 获取聊天记录
     * @param groupId 群号id
     * @return
     * @throws SQLException
     */
    public List<String> initChatHistory(Integer groupId) throws SQLException {
        List<String> list = new ArrayList<>();
        PreparedStatement ps = null;
        ResultSet res = null;
        int count = countRecord(groupId);
        /*
        默认处理恢复100条的信息。
         */
        String sql = "select record,sending_time,user.username " +
                "from chat_record " +
                "left join user on user.id = chat_record.sender " +
                "where `group` = ? " +
                "order by sending_time asc " +
                "limit ?,?";
        ps = con.prepareStatement(sql);
        ps.setInt(1, groupId);
        ps.setInt(2, count-100);
        ps.setInt(3, count);
        res = ps.executeQuery();
        while(res.next()){
            String record = res.getString(1);
            String date = res.getString(2);
            String senderName = res.getString(3);
            String history = date + "  "+ senderName + "说： " + record;
            list.add(history);
        }

        return list;
    }

    public int countRecord(int groupId) throws SQLException {
        con = DBUtil.getConnectDB();
        PreparedStatement ps = null;
        ResultSet res = null;
        String sql = "select count(record) from chat_record where `group` = ?";
        ps = con.prepareStatement(sql);
        ps.setInt(1, groupId);
        res = ps.executeQuery();
        res.next();
        return res.getInt(1);
    }
}
